#! -*- coding: utf-8 -*-

from script_utils import query, oid2nid, get_one2list
from script_utils import models

cols = {
    'vacation_hotel': [
        'id',
        'name',
        'price',
        'is_active',
        'date_added',
        'gds_hotel_id',
    ],
    'vacation_hotelproductorder': [
        'id',
        'planordermtu_id',
        'user_id',
        'device_id',
        'identity',
        'hotel_id',
        'product_id',
        'hotel_name',
        'product_name',
        'hotel_country',
        'hotel_city',
        'checkin_date',
        'checkout_date',
        'rooms',
        'contact_mobile',
        'contact_email',
        'customer_preferences',
        'invoice_title',
        'order_id',
        'total_price',
        'datetime_created',
        'datetime_updated',
        'status',
        'payment_id',
    ],
}

GDS_ORDER_STATUS_MAP = {
    0: 'new',                          # 新建订单
    1: 'new_canceled',                 # 新建订单 未支付 已取消
    2: 'paid_booking',                 # 新建订单 已支付 确认中
    3: 'paid_booksucceeded',           # 支付成功 预订成功
    4: 'paid_bookfailed_notrefunded',  # 支付成功 预订失败 未退款
    5: 'paid_bookfailed_refunded',     # 支付成功 预订失败 已退款
    6: 'paid_canceled_notrefunded',    # 支付成功 已取消 未退款
    7: 'paid_canceled_refunded',       # 支付成功 已取消 已退款
}


def migrate_hotel():
    print 'migrate_hotel start...'

    for row in query('vacation_hotel', cols=cols['vacation_hotel']):
        hotel = dict(zip(cols['vacation_hotel'], row))
        oid = hotel['id']
        hotel['id'] = oid2nid["vacation_hotel"][oid]

        models.Hotel.objects.create(**hotel)

    print 'migrate_hotel end...'


def migrate_hotelorder():
    print 'migrate_hotelorder start...'

    for row in query('vacation_hotelproductorder', cols=cols['vacation_hotelproductorder']):
        hotelorder = dict(zip(cols['vacation_hotelproductorder'], row))
        oid = hotelorder['id']
        hotelorder['id'] = oid2nid["vacation_hotelproductorder"][oid]

        planordermtu_obj_id = oid2nid["vacation_planordermtu"][hotelorder['planordermtu_id']] if hotelorder['planordermtu_id'] else None
        hotelorder['planordermtu'] = planordermtu_obj_id
        del hotelorder['planordermtu_id']

        payment_obj_id = oid2nid["vacation_payment"][hotelorder['payment_id']] if hotelorder['payment_id'] else None
        hotelorder['payment'] = payment_obj_id
        del hotelorder['payment_id']

        hotelorder['status'] = GDS_ORDER_STATUS_MAP[hotelorder['status']]

        models.HotelProductOrder.objects.create(**hotelorder)

    print 'migrate_hotelorder end...'


if __name__ == "__main__":
    migrate_hotel()
    migrate_hotelorder()
